package com.simple.sso.server.filter;

import com.simple.sso.client.utils.SessionStorage;
import com.simple.sso.server.utils.ClientStorage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
@WebFilter(filterName = "sessionFilter", urlPatterns = "/*")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("sso-server SessionFiler init method...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("sso-server SessionFilter doFilter method...");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestUri = request.getRequestURI();
        if (requestUri.endsWith(".js")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 注销请求，放行
        if ("/server/logout".equals(requestUri)) {
            filterChain.doFilter(request, response);
            return;
        }

        if("/server/checkTokenValid".equals(requestUri)){
            filterChain.doFilter(request, response);
            return;
        }

        //这里存储的session为全局session
        HttpSession session = request.getSession();
        //判断是否存在全局会话？如果存在则获取到全局会话的令牌，携带上令牌，重定向到客户端请求。
        if (session.getAttribute("isLogin") != null) {
            //获取请求系统需要跳转到的链接
            String clientUrl = request.getParameter("clientUrl");
            //获取到全局session中保存的令牌
            String token = (String) session.getAttribute("token");
            if (!StringUtils.isEmpty(clientUrl)) {
                ClientStorage.INSTANCE.set(token, clientUrl);
                response.sendRedirect(clientUrl + "?token=" + token);
                return;
            }

            if (!"/server/success".equals(requestUri)) {
                response.sendRedirect("/server/success");
                return;
            }

            filterChain.doFilter(request, response);
            return;
        }

        //如果只是单纯的访问sso-server请求，或者是登录请求，则不拦截 todo 这里contextPath先写死
        if ("/server/".equals(requestUri) || "/server/login".equals(requestUri)
                || "/server/doLogin".equals(requestUri)) {
            filterChain.doFilter(request, response);
            return;
        }

        //默认登录页
        response.sendRedirect("/server/");
    }

    @Override
    public void destroy() {
        System.out.println("sso-server SessionFilter destroy method...");
    }
}
